package io.qar.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.AES;
import io.qar.commons.tools.utils.AESUtils;
import io.qar.dto.AccessDTO;
import io.qar.dto.LoginDTO;
import io.qar.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @program: qar-cloud
 * @description:
 * @author: yyyyjinying
 * @create: 2023-10-08 13:42
 **/
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Value("${clientId}")
    private String clientId;
    @Value("${clientSecret}")
    private String clientSecret;

    @Value("${AES.decryptKey}")
    private String decryptKey;

    @Value("${AES.decryptIv}")
    private String decryptIv;

    private String getPassword(String password){
//        AES解密
        AES aes = new AES("CBC", "PKCS7Padding",
                // 密钥，可以自定义
                decryptKey.getBytes(),
                // iv加盐，按照实际需求添加
                decryptIv.getBytes());
        return aes.decryptStr(password);
    }


    @Override
    public Map login(LoginDTO loginDTO) {
        ServiceInstance choose = loadBalancerClient.choose("qar-auth-server");
        String url = choose.getUri().toString() + "/auth/oauth/token";
        MultiValueMap<String, String> headers = new LinkedMultiValueMap();
        byte[] bytes = StrUtil.format("{}:{}", clientId, clientSecret).getBytes();
        String encode = Base64.encode(bytes);
        headers.add("Authorization", "Basic " + encode);

        MultiValueMap<String, String> body = new LinkedMultiValueMap();
        body.add("username", loginDTO.getUsername());
        body.add("password", getPassword(loginDTO.getPassword()));
        body.add("grant_type", loginDTO.getGrant_type());
        // 验证码
        body.add("captcha", loginDTO.getCaptcha());
        body.add("uuid", loginDTO.getUuid());

        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<MultiValueMap>(body, headers);
        // basic auth
        ResponseEntity<Map> res = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        Map bodyReponse = res.getBody();
        return bodyReponse;
    }
}
